<template>
  <div class="warp_auto">
    <div class="warp_top">
      <div class="jiansuo-box">
        <span class="label">类型名称：</span>
        <el-input
          v-model="typeName"
          class="input"
          placeholder="请输入类型名称"
        />
      </div>

      <div class="jiansuo-box">
        <span class="label">类型状态：</span>
        <el-select
          v-model="typeStatus"
          placeholder="请选择状态"
          clearable
          class="input"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>

      <el-button
        type="primary"
        icon="el-icon-search"
        class="btn"
        @click="btnQueryTypelist"
      >检索
      </el-button>
      <el-button
        type="primary"
        class="btn"
        @click="add"
      >新增类型
      </el-button>
    </div>

    <!-- 类型（表格）-->
    <el-card>
      <el-table
        :data="arrlist"
        style="width: 100%"
        height="540"
        stripe
        :header-cell-style="{ background: '#d2e0f9', color: '#606266' }"
      >
        <el-table-column
          type="index"
          width="90"
          label="序号"
          align="center"
        />
        <el-table-column label="类型名称" align="center">
          <template slot-scope="scope">
              <span style="margin-left: 10px">{{
                  scope.row.dict_template_name
                }}</span>
          </template>
        </el-table-column>
        <el-table-column
          property="status"
          width="300"
          label="状态"
          align="center"
          header-align="center"
        >
          <template scope="scope">
            <el-switch
              v-model="scope.row.status"
              class="switch-btn"
              inactive-text="禁用"
              active-text="启用"
              :active-value="1"
              :inactive-value="0"
              active-color="#02538C"
              inactive-color="#B9B9B9"
              @change="changeSwitchslei(scope.$index, scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.sort_num }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              :disabled = '!operationJudge(scope.row)'
              @click="templateSetCick(scope.row)"
            >设置
            </el-button>
            <el-button
              size="mini"
              :disabled = '!operationJudge(scope.row)'
              @click="handleEditss(scope.row)"
            >编辑
            </el-button>
            <el-popover
              :ref="`popover-${scope.$index}`"
              trigger="click"
              placement="top"
              width="100"
            >
              <p class="el-icon-warning">确定删除</p>
              <div style="text-align: right; margin: 0">
                <el-button
                  size="mini"
                  type="text"
                  @click="no(scope)"
                >取消
                </el-button>
                <el-button
                  type="primary"
                  size="mini"
                  @click="yess(scope)"
                >确定
                </el-button>
              </div>
              <el-button
                slot="reference"
                size="mini"
                :disabled = '!operationJudge(scope.row)'
                style="margin-left: 10px"
                type="danger"
              >删除
              </el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <div class="paging">
        <el-pagination
          :current-page="start"
          :page-size="PageSize"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCounts"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!--    编辑护理模板类型-->
    <el-dialog
      title="编辑护理模板类型"
      :visible.sync="typeEditdialogVisible"
      :show-close="false"
      width="500px"
    >
      <el-form class="form" label-width="80px">
        <el-form-item label="类型名称 : ">
          <el-input v-model="editDialogInfo.dict_template_name"/>
        </el-form-item>

        <el-form-item label="排序 : ">
          <el-input v-model="editDialogInfo.sort_num"/>
        </el-form-item>
        <el-form-item label="状态 : ">
          <el-switch
            v-model="editDialogInfo.status"
            class="switch-btn"
            inactive-text="禁用"
            active-text="启用"
            :active-value="1"
            :inactive-value="2"
            active-color="#02538C"
            inactive-color="#B9B9B9"
          />
        </el-form-item>

      </el-form>
      <div slot="footer">
        <el-button @click="typeEditdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="typeEditSaveClick">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 新增护理模板类型-->
    <el-dialog
      title="新增护理模板类型"
      :visible.sync="typeDialogVisble"
      :close-on-click-modal="false"
      :show-close="false"
      width="500px"
    >
      <el-form
        ref="leixFrom"
        :model="leixFrom"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="类型名称 : " prop="dicTemplateName">
          <el-input
            v-model="leixFrom.dicTemplateName"
            placeholder="请输入类型名称"
          />
        </el-form-item>
        <el-form-item label="排序 : " prop="sortNum">
          <el-input
            v-model="leixFrom.sortNum"
          />
        </el-form-item>
        <el-form-item label="状态 : " prop="status">
          <el-switch
            v-model="leixFrom.status"
            class="switch-btn"
            inactive-text="禁用"
            active-text="启用"
            :active-value="1"
            :inactive-value="0"
            active-color="#02538C"
            inactive-color="#B9B9B9"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="typeDialogVisble = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submitFormleix('leixFrom')"
        >保 存
        </el-button>
      </div>
    </el-dialog>

    <!-- switch-type -->
    <el-dialog
      title="状态更新"
      :visible.sync="switchDialog"
      :show-close="false"
    >
      <span>
        <i class="el-icon-warning"/>此操作将会改变开关状态, 是否继续?
      </span>
      <span slot="footer">
        <el-button
          @click="(switchDialog = false), cancelSwitchlei()"
        >取 消</el-button>
        <el-button
          type="primary"
          @click="(switchDialog = false), updataSwitchlei()"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import {
  templateDictionaryupdate,
  queryList,
  templateDictionaryinsert,
  templateDictionarydelete,
  templateDictionaryedit
} from '@/api/table'

export default {
  data() {
    return {
      switchDialog: false, // 开关-类型
      typeSwitchId: '',
      typeSwitchStatus: '',
      typeDialogVisble: false,
      typeName: '',
      typeStatus: '',
      // 控制弹窗 显示
      typeEditdialogVisible: false,
      editDialogInfo: {},
      listarr: null,
      listLoading: true,
      loading: false,
      leixFrom: {
        dicTemplateName: '',
        status: 1,
        sortNum: ''
      },
      rules: {
        templateItemName: [
          {required: true, message: '请输入模板名称', trigger: 'blur'}
        ],
        sortNum: [{required: true, message: '请输入排序', trigger: 'blur'}],
        dicTemplateName: [
          {required: true, message: '请输入模板类型名称', trigger: 'blur'}
        ],
        templateId: [
          {required: true, message: '请选择模板类型', trigger: 'change'}
        ]
      },
      options: [
        {
          id: '1',
          value: 1,
          label: '启用'
        },
        {
          id: '0',
          value: 0,
          label: '禁用'
        }
      ],
      arrlist: [],
      arrTypelist: [],
      arrTypeAllList: [],
      start: 1, // 默认显示第几页
      totalCount: 0, // 总条数，根据接口获取数据长度(注意 : 这里不能为空)
      totalCounts: 0,
      pgeSizes: [10, 20, 30, 40], // 个数选择器（可修改）
      PageSize: 10, // 默认每页显示的条数（可修改）
    }
  },
  created() {
    this.queryTypeList(this.PageSize, this.start);
  },
  methods: {
    //操作权限判断
    operationJudge(rowData){
      // if(rowData.dict_template_name == '自定义引流管'){
      //   if(this.$store.state.user.roles[0] == '重症护士长' || this.$store.state.user.roles[0] == '超级管理员'){
      //     return true;
      //   }else{
      //     return false;
      //   }
      // }
      return true;
    },
    //类型检索
    queryTypeList(pageSize, start) {
      queryList({
        size: pageSize,
        start: start,
        dicTemplateName: this.typeName,
        status: this.typeStatus === '' ? null : this.typeStatus
      }).then((res) => {
        this.arrlist = res.data
        this.totalCounts = res.totalCount
      })

    },
    add() {
      this.leixFrom = {
        dicTemplateName: '',
        status: 1,
        sortNum: ''
      };
      this.typeDialogVisble = true;
    },
    // 新增类型
    submitFormleix(leixFrom) {
      this.$refs[leixFrom].validate((valid) => {
        if (valid) {
          templateDictionaryinsert(this.leixFrom).then((res) => {
            if (res.code === 200) {
              //清空数据
              this.resetForm(leixFrom);

              this.queryTypeList(
                this.PageSize,
                this.start
              )
              this.typeDialogVisble = false;
              this.$message({
                message: "添加成功",
                type: "success",
                duration: 1500,
              });

            } else {
              this.$message({
                message: "添加失败",
                type: "warning",
                duration: 1500,
              });
              this.typeDialogVisble = true
            }
          })

        } else {
          this.$message({
            message: '请填写必填项！',
            type: 'warning',
            duration: 1500
          })
          this.typeDialogVisble = true

          return false
        }
      })
    },
    // 删除类型
    yess(scope) {
      // 可以在这里执行删除数据的回调操作.......删除操作......
      const id = scope.row.id
      templateDictionarydelete({id: id}).then((res) => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.queryTypeList(this.PageSize, this.start)
      })
      scope._self.$refs[`popover-${scope.$index}`].doClose()
    },
    no(scope) {
      this.$message('取消删除')
      scope._self.$refs[`popover-${scope.$index}`].doClose()
    },

    changeSwitchslei(index, row) {
      this.typeSwitchId = row.id
      this.typeSwitchStatus = row.status
      this.switchDialog = true
    },

    // 保存开关状态-类型-取消
    cancelSwitchlei() {
      this.queryTypeList(this.PageSize, this.start) // 重新获取表格
    },

    // 保存开关状态-类型-确认
    updataSwitchlei() {
      templateDictionaryupdate({
        id: this.typeSwitchId,
        status: this.typeSwitchStatus
      }).then((res) => {
        this.queryTypeList(this.PageSize, this.start)
      })
    },
    // 类型检索
    btnQueryTypelist() {
      this.start = 1;
      this.queryTypeList(this.PageSize, this.start)
    },
    // 每页显示的条数
    handleSizeChange(val) {
      // 改变每页显示的条数
      this.PageSize = val
      // 点击每页显示的条数时，显示第一页
      this.queryTypeList(this.PageSize, this.start) // 类型

      // 注意 : 在改变每页显示的条数时，要将页码显示到第一页
      this.start = 1
    },
    // 显示第几页
    handleCurrentChange(val) {
      // 改变默认的页数
      this.start = val
      // 切换页码时，要获取每页显示的条数
      this.queryTypeList(this.PageSize, this.start) // 类型
    },
    //打开具体的模板设置页面
    templateSetCick(info) {
      this.$router.push({
        path: '/dataAnalysis/templateSet',
        query: {
          templateTypeId: info.id,
          templateTypeName: info.dict_template_name
        }
      })
    },
    //打开编辑类型页面
    handleEditss(info) {
      this.typeEditdialogVisible = true;
      this.editDialogInfo = info;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 修改父组件传过来的值
    typeEditSaveClick() {
      templateDictionaryedit({
        id: this.editDialogInfo.id,
        status: this.editDialogInfo.status,
        dicTemplateName: this.editDialogInfo.dict_template_name,
        sortNum: Number(this.editDialogInfo.sort_num)
      }).then((res) => {
        if (res.code === 200) {
          this.$message({message: "编辑成功", type: "success"});
          this.typeEditdialogVisible = false;
        } else {
          this.$message({message: "编辑失败", type: "warning"});
        }
      })
    }
  }
}

</script>
